import { GlobalValue } from "@/GlobalValue";
import { clearLoginInfo, useLoginInfo } from "@/hooks/useLoginInfo";
import { useTranslation } from "@/i18n";
import LogoutOutlined from "@ant-design/icons/lib/icons/LogoutOutlined";
import UserOutlined from "@ant-design/icons/lib/icons/UserOutlined";
import { SSO } from "@nsb/user-center-sso-plugin";
import { Button, Dropdown, Typography } from "antd";
import { ItemType } from "antd/es/menu/interface";
import { useMemo } from "react";
import { TopBarIconButton } from "./TopBarIconButton";
import { LoadingOutlined } from "@ant-design/icons";
const { Text } = Typography;
enum MenuItemKey {
  UserCenter = 'user_center',
  Logout = 'logout',
}

interface IUseMenuItemsOpts {
  has_login?: boolean;
}
function useMenuItems(opts: IUseMenuItemsOpts): ItemType[] {
  const { has_login } = opts;
  const { t } = useTranslation();
  return useMemo(() => {
    const ret: ItemType[] = [{
      key: MenuItemKey.UserCenter,
      icon: <UserOutlined />,
      label: t("common.user_center"),
      onClick: () => window.open(__USER_CENTER_SSO_ORIGIN__)
    }]
    if (has_login) {
      ret.push({
        key: MenuItemKey.Logout,
        icon: <LogoutOutlined />,
        label: t("common.logout"),
        onClick: () =>
          new SSO({ path: '/logout', origin: __USER_CENTER_SSO_ORIGIN__, device: "goltach_windows" }).on('logout', clearLoginInfo)
      })
    }
    return ret;
  }, [t, has_login])
}
interface IUserDropdownProps {
  onClickLogin?(): void;
  pending?: boolean;
}
export default function UserDropdown(props: IUserDropdownProps) {
  const { onClickLogin, pending } = props
  const { t } = useTranslation();
  const name = useLoginInfo('name');
  const has_login = !!name
  const menuItems = useMenuItems({ has_login });
  const { smallScreen } = GlobalValue.use(0);
  const inner = useMemo(() => {
    if (smallScreen) return <UserOutlined />;
    if (typeof name === 'string') return <Text>你好, {name}</Text>
    return t("common.not_login")
  }, [smallScreen, name])
  if (pending) {
    return (
      <Button type='text' title='正在自动登录, 请稍等...' onClick={onClickLogin}>
        <LoadingOutlined /> 登录中...
      </Button>
    )
  } else if (!has_login) {
    return (
      <Button type='text' onClick={onClickLogin}>
        {t("common.login")}
      </Button>
    )
  } else {
    return (
      <Dropdown
        menu={{ items: menuItems }}
        placement="bottom"
        arrow
        trigger={['click']} >
        <TopBarIconButton >
          {inner}
        </TopBarIconButton>
      </Dropdown>
    )
  }
}